<?php

namespace App\Jobs;

use App\Libraries\rong_cloud_sdk\Rongyun;
use App\Models\ClientUserRongcloud;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class RongcloudHistory implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return bool
	 * 融云服务器的历史记录有1小时延迟，这边做2小时延迟，避免中间时间差的问题
	 * 一次获取一小时的，2017051017 表示获取 5月10日 17-18点的数据
	 *
     */
    public function handle()
    {
    	$time = date('YmdH',strtotime('-2 hours'));
//    	$time = '2017052310';
    	$time2 = date('Y-m-d-H',strtotime('-2 hours'));
//    	$time2 = '2017-05-23-10';
		$rongyun = new Rongyun();
		$history = $rongyun->message()->getHistory($time);
		$zip_url = $history['url'];
		// 如果没有聊天记录，就不会有url
		if(!$zip_url){
//			logger($time.'无聊天记录，中断执行');
			return false;
		}
		$resource = curl_get($zip_url);
		$file_name_pre = './storage/rongcloud_history';
		if(!is_dir($file_name_pre)){
			mkdir($file_name_pre,0777,true);
		}
		$uniqid = uniqid();
		$file_name = $file_name_pre.'/'.$uniqid.'.zip';
		file_put_contents($file_name,$resource);
		// Zip 解压
		$zip = new \ZipArchive();
		$zip->open($file_name);
		$zip->extractTo($file_name_pre.'/');
		$zip->close();
		$history_json = file_get_contents($file_name_pre.'/'.$time2);
		$history_array = explode("\r\n",$history_json);
		foreach($history_array as $v){
			if(empty($v)){
				continue;
			}
			$date = str_replace('/','-',strstr($v,'{',true));
			$json = json_decode(strstr($v,'{'),true);
			$add = [
				'from_uid'		=> $json['fromUserId'],
				'to_uid'		=> $json['targetId'],
				'type'			=> $json['classname'],
				'source'		=> $json['source'],
				'content'		=> json_encode($json['content']),
				'content_id'	=> $json['msgUID'],
				'created_at'	=> $date,
			];
			$exist = ClientUserRongcloud::where(['content_id'=>$json['msgUID']])->count();
			if($exist){
				continue;
			}
			ClientUserRongcloud::create($add);
		}
		// 处理完后删除源文件
		unlink($file_name);
		unlink($file_name_pre.'/'.$time2);
//		logger($time2.'聊天历史插入完成，共'.count($history_array));
		return true;
	}
    
    public function failed($exception = null)
	{
		send_mail('512511253@qq.com','【慧城】获取融云聊天历史队列失败,时间：'.time2date());
	}
}
